<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2019/12/2
 * Time: 14:25
 */

namespace app\api\controller;


use think\Db;

class Apilogin extends Base
{
    //车辆网信息请求地址
    public $car_url = 'http://cctruck.project.g7s.huoyunren.com/service.php?method=truck.ccappapi.getVehicleTeam';
    
    /**
     * 发送验证码
     * @return \think\response\Json|void
     * phone       填写的手机号
     * type        发送场景   1 账号密码注册   2 找回密码
     * types       传1
     * yzm         图形验证码
     * send_type   发送场景（用于判断发送次数）1 快捷登录   2 账号密码注册   3 找回密码
     */
    public function getPhoneCode()
    {
        $params = input('');
        
        if(trim($params['phone'], ' ') == '') {
            return json(['status' => 0, 'msg' => '请输入手机号']);
        }
        if(!preg_match("/^1[3456789]\d{9}$/", $params['phone'])) {
            return json(['status' => 0, 'msg' => '手机号格式不正确']);
        }
        $userInfo = Db::table('up_u_user')->where('user_phone', $params['phone'])->find();
        if(!empty($userInfo) && isset($params['type']) && $params['type'] == 1) { //注册
            if($userInfo['user_status'] == 2){
                return json(['status' => 0, 'msg' => '该手机号注册的账号已被删除，请换个手机号注册']);
            }elseif($userInfo['user_status'] == 3){
                return json(['status' => 0, 'msg' => '该手机号注册的账号已被冻结，请换个手机号注册']);
            }else{
                return json(['status' => 0, 'msg' => '该手机号已注册']);
            }
        }
        if(empty($userInfo) && isset($params['type']) && $params['type'] == 2) { //找回密码
            return json(['status' => 0, 'msg' => '该账号不存在']);
        }
        
        // 图形验证码
        if(isset($params['types']) && $params['types'] == 1){
            $yzm  = input('yzm');
            $yzm_data = Db::table('up_phonecode')->where('phone',$params['phone'])->find();
            if($yzm_data['yzm'] != $yzm){
                return json(['status'=>22,'msg'=>'图形验证码错误']);
            }
            if($yzm_data['yzm_status'] != 1){
                return json(['status'=>22,'msg'=>'此图形验证码已使用，请重新获取']);
            }
            Db::table('up_phonecode')->where('phone',$params['phone'])->update(['yzm_status'=>2]);
        }
    
        // 判断不同场景下的发送次数
        $startTime = strtotime(date('Y-m-d 00:00:00'));//当天的起始时间
        $endTime = strtotime(date('Y-m-d 23:59:59'));//当天的结束时间
        $where = [];
        $where['phone'] = $params['phone'];
        $where['yzm_type'] = $params['send_type'];
        $where['time'] = ['between', [$startTime, $endTime]];
        $num = Db::table('up_phonecode')->where($where)->count('id');
        if($num >= 5) {
            return json(['status' => 0, 'msg' => '今日获取次数已用完，明天再来吧～']);
        }
        $code = GetRandCode();//6位数验证码
        $sendres = $this->ypwSms($code, $params['phone']);//发送验证码
        $sendres = json_decode($sendres, true);
        if($sendres['code'] != 0) {//发送不成功
            return json(['status' => 0, 'msg' => $sendres['msg']]);
        } else {
            $data = [
                'phone' => $params['phone'],//发送的手机号
                'code' => $code,//验证码
                'time' => time(),//验证码发送的时间戳
                'date_time' => date('Y-m-d H:i:s'),//日期格式
                'yzm_type' => $params['send_type']
            ];
            $res = Db::table('up_phonecode')->insert($data);
            if(!$res) {
                return json(['status' => 0, 'msg' => '数据库操作失败']);
            }
            return json(['status' => 200, 'msg' => $code]);
        }
    }
    
    /**
     * 图形验证码
     */
    public function pictureyzm(){
        $phone = input('phone');
        header("content-type:image/png");
        $validateLength=4;
        $strToDraw="";
        $chars=[
            "0","1","2","3","4",
            "5","6","7","8","9",
            "a","b","c","d","e","f","g",
            "h","i","j","k","l","m","n",
            "o","p","q","r","s","t",
            "u","v","w","x","y","z",
            "A","B","C","D","E","F","G",
            "H","I","J","K","L","M","N",
            "O","P","Q","R","S","T",
            "U","V","W","X","Y","Z"
        ];
        $imgW=80;
        $imgH=25;
        $imgRes=imagecreate($imgW,$imgH);
        $imgColor=imagecolorallocate($imgRes,255,255,100);
        $color=imagecolorallocate($imgRes,0,0,0);
        for($i=0;$i<$validateLength;$i++){
            $rand=rand(0,9);
            $strToDraw=$strToDraw.$chars[$rand];
        }
        imagestring($imgRes,5,20,5,$strToDraw,$color);
        for($i=0;$i<100;$i++){
            imagesetpixel($imgRes,rand(0,$imgW),rand(0,$imgH),$color);
        }
        $where['phone'] = $phone;
        $res= Db::table('up_phonecode')->where($where)->find();
        if($res['id']!=''){ // 不等于空的时候
            $data['yzm'] = $strToDraw;
            $data['yzm_status'] = 1;
            
            Db::table('up_phonecode')->where($where)->update($data);
        }else{//等于空空
            $data['yzm'] = $strToDraw;
            $data['phone'] = $phone;
            Db::table('up_phonecode')->insert($data);
        }
        imagepng($imgRes);
        imagedestroy($imgRes);exit;
    }
    
    /**
     * 手机号快捷注册（作废）
     * @return \think\response\Json
     * phone    手机号
     * code     验证码
     */
    public function phoneRegister(){
        $phone = trim(input('phone'), ' ');
        $code = trim(input('code'), ' ');
        if($phone == '') {
            return json(['status' => 0, 'msg' => '请输入手机号']);
        }
        if($code == '') {
            return json(['status' => 0, 'msg' => '请输入验证码']);
        }
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)) {
            return json(['status' => 0, 'msg' => '手机号格式不正确']);
        }
        
        $user = Db::table('up_u_user')->where('user_phone', $phone)->find();
        if(!empty($user)){
            if($user['user_status'] == 2){
                return json(['status' => 0, 'msg' => '该手机号注册的账号已被删除，请换个手机号注册']);
            }elseif($user['user_status'] == 3){
                return json(['status' => 0, 'msg' => '该手机号注册的账号已被冻结，请换个手机号注册']);
            }else{
                return json(['status' => 0, 'msg' => '该手机号已注册']);
            }
        }
    
        //验证验证码
        $res = Db::table('up_phonecode')
            ->where('phone', $phone)
            ->order('time desc')
            ->limit(1)
            ->find();
        if($code != $res['code']) {
            return json(['status' => 0, 'msg' => '验证码错误']);
        }
        // 10分钟超时
        $now = time();
        if($now - $res['time'] >= 1801) {
            return json(['status' => 0, 'msg' => '验证码超时']);
        }
        if($res['status'] == 1) {
            return json(['status' => 0, 'msg' => '验证码已使用']);
        }
    
        $token = md5(date('YmdHis') . rand(100000, 999999));
        $insert = [
            'user_phone' => $phone,
            'user_token' => $token,
            'user_time' => date('Y-m-d H:i:s'),
            'user_last_time' => date('Y-m-d H:i:s'),
        ];
        $user_id = Db::table('up_u_user')->insertGetId($insert);
        
        if($user_id){
            //修改验证码状态
            Db::table('up_phonecode')->where('id', $res['id'])->setField('status', 1);
            //注册成功后自动登录
            $userInfo = Db::table('up_u_user')->where('user_id', $user_id)->find();
            return json(['status' => 200, 'msg' => $userInfo]);
        }else{
            return json(['status' => 0, 'msg' => '注册失败']);
        }
    }
    
    /**
     * 密码注册
     * @return \think\response\Json
     * phone     手机号
     * code      验证码
     * fpwd      第一次输入的密码
     * spwd      第二次输入的密码
     */
    public function passwordRegister(){
        $phone = input('phone');
        $code = trim(input('code'), ' ');
        $fpwd = input('fpwd'); // 第一次输入的密码
        $spwd = input('spwd'); // 第二次输入的密码
        $district = input('district');
        // 必填项
        if($phone == '' || $code == '' || $fpwd == '' || $spwd == ''){
            return json(['status' => 0, 'msg' => '有未填项']);
        }
        // 手机号格式
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)) {
            return json(['status' => 0, 'msg' => '请输入正确的手机号']);
        }
        $user = Db::table('up_u_user')->where('user_phone', $phone)->find();
        if(!empty($user)){
            if($user['user_status'] == 2){
                return json(['status' => 0, 'msg' => '该手机号注册的账号已被删除，请换个手机号注册']);
            }elseif($user['user_status'] == 3){
                return json(['status' => 0, 'msg' => '该手机号注册的账号已被冻结，请换个手机号注册']);
            }else{
                return json(['status' => 0, 'msg' => '该手机号已注册']);
            }
        }
        // 密码
        if($fpwd != $spwd){
            return json(['status' => 0, 'msg' => '两次输入的密码不一致']);
        }
        //验证验证码
        $res = Db::table('up_phonecode')
            ->where('phone', $phone)
            ->order('time desc')
            ->limit(1)
            ->find();
        if($code != $res['code']) {
            return json(['status' => 0, 'msg' => '验证码错误']);
        }
        // 10分钟超时
        $now = time();
        if($now - $res['time'] >= 1801) {
            return json(['status' => 0, 'msg' => '验证码超时']);
        }
        if($res['status'] == 1) {
            return json(['status' => 0, 'msg' => '验证码已使用']);
        }
    
        $draw_times = Db::table('up_about')->where('about_id', 101)->value('about_content');
        $token = md5(date('YmdHis') . rand(100000, 999999));
        $user_car_id = 'c' . $phone;
        $insert = [
            'user_phone' => $phone,
            'user_token' => $token,
            'user_password' => md5($fpwd),
            'user_time' => date('Y-m-d H:i:s'),
            'user_last_time' => date('Y-m-d H:i:s'),
            'user_car_id' => $user_car_id,
            'user_draw_times' => $draw_times
        ];
        //=====  获取车辆网信息 ========
        $request = $this->car_url . '&account=' . $user_car_id;
        $data = kd_http($request);
        if($data['procStatus'] == 0){
            $team = end($data['teams']);
            $num = count($data['teams']);
            $insert['user_team_id'] = $team['teamId'];
            $insert['user_car_num'] = $num;
        }
        //============================
        Db::startTrans();
        try{
            // 用户表
            $user_id = Db::name('u_user')->insertGetId($insert);
            // 抽奖次数明细
            Db::table('up_draw_info')
                ->insert([
                    'info_user_id' => $user_id,
                    'info_draw_times' => $draw_times,
                    'info_times_desc' => '注册赠送',
                    'info_times_type' => 1,
                    'info_time' => date('Y-m-d H:i:s'),
                    'info_district' => $district,
                ]);
            //修改验证码状态
            Db::table('up_phonecode')->where('id', $res['id'])->setField('status', 1);
            //注册成功后自动登录
            $userInfo = Db::table('up_u_user')->where('user_id', $user_id)->find();
            Db::commit();
            return json(['status' => 200, 'msg' => $userInfo]);
        }catch(\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 账号密码登录
     * @return \think\response\Json
     * phone    手机号
     * pwd      密码
     */
    public function passwordLogin(){
        $phone = trim(input('phone'), ' ');
        $pwd = input('pwd');
        // 必填项
        if($phone == '' || $pwd == ''){
            return json(['status' => 0, 'msg' => '有未填项']);
        }
    
        // 手机号格式
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)) {
            return json(['status' => 0, 'msg' => '请输入正确的手机号']);
        }
    
        $user = Db::table('up_u_user')->where('user_phone', $phone)->find();
        if(empty($user)){
            return json(['status' => 0, 'msg' => '账号不存在']);
        }
    
        $password = md5($pwd);
        if(!empty($user) && $password != $user['user_password']){
            return json(['status' => 0, 'msg' => '密码错误']);
        }
    
        if($user['user_status'] == 3) {
            return json(['status' => 0, 'msg' => '该账号已被冻结']);
        }
        if($user['user_status'] == 2) {
            return json(['status' => 0, 'msg' => '该账号已被删除，请联系管理员']);
        }
        $token = $token = md5(date('YmdHis') . rand(100000, 999999));
        $data['user_last_time'] = date('Y-m-d H:i:s');
        $data['user_token'] = $token;
        $res = Db::table('up_u_user')->where('user_phone', $phone)->update($data);
        if($res){
            $userInfo = Db::table('up_u_user')->where('user_phone', $phone)->find();
            return json(['status' => 200, 'msg' => $userInfo]);
        }else{
            return json(['status' => 0, 'msg' => '登录失败']);
        }
    }
    
    /**
     * 手机号验证码登录/注册
     * @return \think\response\Json
     * phone    手机号
     * code     验证码
     */
    public function phoneLogin(){
        $phone = trim(input('phone'), ' ');
        $code = trim(input('code'), ' ');
        $district = input('district');
        // 必填项
        if($phone == '' || $code == ''){
            return json(['status' => 0, 'msg' => '有未填项']);
        }
    
        // 手机号格式
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)) {
            return json(['status' => 0, 'msg' => '请输入正确的手机号']);
        }
    
        $user = Db::table('up_u_user')->where('user_phone', $phone)->find();
//        if(empty($user)){
//            return json(['status' => 0, 'msg' => '账号不存在']);
//        }
    
        if($user['user_status'] == 3) {
            return json(['status' => 0, 'msg' => '该账号已被冻结']);
        }
        if($user['user_status'] == 2) {
            return json(['status' => 0, 'msg' => '该账号已被删除，请联系管理员']);
        }
        
        //=========验证验证码
        $res = Db::table('up_phonecode')
            ->where('phone', $phone)
            ->order('time desc')
            ->limit(1)
            ->find();
        if($code != $res['code']) {
            return json(['status' => 0, 'msg' => '验证码错误']);
        }
        // 10分钟超时
        $now = time();
        if($now - $res['time'] >= 1801) {
            return json(['status' => 0, 'msg' => '验证码超时']);
        }
        if($res['status'] == 1) {
            return json(['status' => 0, 'msg' => '验证码已使用']);
        }
        
        $token = md5(date('YmdHis') . rand(100000, 999999));
        $data['user_last_time'] = date('Y-m-d H:i:s');
        $data['user_token'] = $token;
        if($user){ // 登录
            $result = Db::table('up_u_user')->where('user_phone', $phone)->update($data);
            if($result){
                //修改验证码状态
                Db::table('up_phonecode')->where('id', $res['id'])->setField('status', 1);
                $userInfo = Db::table('up_u_user')->where('user_phone', $phone)->find();
                // 判断用户有没有设置密码
                if(empty($userInfo['user_password'])){
                    return json(['status' => 201, 'msg' => '']);
                }
                return json(['status' => 200, 'msg' => $userInfo]);
            }else{
                return json(['status' => 0, 'msg' => '登录失败']);
            }
        }else{
            $draw_times = Db::table('up_about')->where('about_id', 101)->value('about_content');
            $data['user_phone'] = $phone;
            $data['user_time'] = date('Y-m-d H:i:s');
            $user_car_id = 'c' . $phone;
            $data['user_car_id'] = $user_car_id;
            $data['user_draw_times'] = $draw_times;
            //=====  获取车辆网信息 ========
            $request = $this->car_url . '&account=' . $user_car_id;
            $data_request = kd_http($request);
            if($data_request['procStatus'] == 0){
                $team = end($data_request['teams']);
                $num = count($data_request['teams']);
                $data['user_team_id'] = $team['teamId'];
                $data['user_car_num'] = $num;
            }
            //============================
            Db::startTrans();
            try{
                // 用户
                $userid = Db::table('up_u_user')->insertGetId($data);
                // 抽奖次数明细
                Db::table('up_draw_info')
                    ->insert([
                        'info_user_id' => $userid,
                        'info_draw_times' => $draw_times,
                        'info_times_desc' => '注册赠送',
                        'info_times_type' => 1,
                        'info_time' => date('Y-m-d H:i:s'),
                        'info_district' => $district,
                    ]);
                //修改验证码状态
                Db::table('up_phonecode')->where('id', $res['id'])->setField('status', 1);
                Db::commit();
                return json(['status' => 201, 'msg' => true]);
            }catch(\Exception $e){
                Db::rollback();
                return json(['status' => 0, 'msg' => $e->getMessage()]);
            }
        }
    }
    
    /**
     * 找回密码第一步
     * @return \think\response\Json
     * phone    手机号
     * code     验证码
     */
    public function findPwdF(){
        $phone = trim(input('phone'), ' ');
        $code = trim(input('code'), ' ');
        
        if($phone == '' || $code == ''){
            return json(['status' => 0, 'msg' => '有未填项']);
        }
    
        // 手机号格式
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)) {
            return json(['status' => 0, 'msg' => '请输入正确的手机号']);
        }
        $user = Db::table('up_u_user')->where('user_phone', $phone)->find();
        if(empty($user)){
            return json(['status' => 0, 'msg' => '账号不存在']);
        }
    
        //=========验证验证码
        $res = Db::table('up_phonecode')
            ->where('phone', $phone)
            ->order('time desc')
            ->limit(1)
            ->find();
        if($code != $res['code']) {
            return json(['status' => 0, 'msg' => '验证码错误']);
        }
        // 10分钟超时
        $now = time();
        if($now - $res['time'] >= 1801) {
            return json(['status' => 0, 'msg' => '验证码超时']);
        }
        if($res['status'] == 1) {
            return json(['status' => 0, 'msg' => '验证码已使用']);
        }
        //修改验证码状态
        Db::table('up_phonecode')->where('id', $res['id'])->setField('status', 1);
        return json(['status' =>200, 'msg' => 'ok']);
    }
    
    /**
     * 找回密码第二步/设置密码
     * @return \think\response\Json
     * phone     手机号
     * newPwd1   新密码
     * newPwd2   确认新密码
     * type      1 找回密码第二步    2 设置密码
     */
    public function findPwdS(){
        $phone = input('phone');
        $newPwd1 = input('newPwd1');
        $newPwd2 = input('newPwd2');
        $type = input('type');
        if($newPwd1 == '' || $newPwd2 == ''){
            return json(['status' => 0, 'msg' => '有未填项']);
        }
        
        if($newPwd1 !== $newPwd2){
            return json(['status' => 0, 'msg' => '两次输入的密码不一样']);
        }
        
        $update = [
            'user_password' => md5($newPwd1),
            'user_update_time' => date('Y-m-d H:i:s')
        ];
        if($type == 2){
            $token = $token = md5(date('YmdHis') . rand(100000, 999999));
            $update['user_last_time'] = date('Y-m-d H:i:s');
            $update['user_token'] = $token;
        }
        $res = Db::table('up_u_user')->where('user_phone', $phone)->update($update);
        if($res){
            $user = Db::table('up_u_user')->where('user_phone', $phone)->find();
            return json(['status' => 200, 'msg' => $user]);
        }else{
            return json(['status' => 0, 'msg' => '操作失败']);
        }
    }
    
    /**
     * 其他
     * @return \think\response\Json
     * type  1 400热线  2 功能介绍  3 法律声明  4 平台协议  5 用户协议  6 隐私协议
     */
    public function userOther(){
        $type = input('type');
        $about = Db::table('up_about')->where('about_id', $type)->value('about_content');
        if($about){
            return json(['status' => 200, 'msg' => $about]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 获取省市区的三维数组
     * @return \think\response\Json
     */
    public function getArea()
    {
        $provinceLists = Db::name('area')->where('level', 1)->select(); // 省
        $cityLists = Db::name('area')->where('level', 2)->select(); // 市
        $districtLists = Db::name('area')->where('level', 3)->select(); // 区
        foreach($cityLists as $k => $city) {
            foreach($districtLists as $kk => $district) {
                if($city['district_id'] == $district['pid']) {
                    $cityLists[$k]['qu'][] = $district;
                }
            }
        }
        foreach($provinceLists as $key => $province) {
            foreach($cityLists as $ke => $city) {
                if($province['district_id'] == $city['pid']) {
                    $provinceLists[$key]['city'][] = $city;
                }
            }
        }
        return json(['status' => 200, 'msg' => $provinceLists]);
    }
}